package com.hefan.main.rpcfilter;

import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSON;
import com.hefan.common.util.DynamicProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.Profiler;
import org.slf4j.profiler.ProfilerRegistry;

/**
 * @author: ninglijun
 * @date: 15/12/9
 * @time: 上午10:53
 * @description:
 */
public class MonitorFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(MonitorFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String itf = invocation.getAttachment("interface");
        String methodName = invocation.getMethodName();
        String key = itf + ":" + methodName;
        int thredshold = DynamicProperties.getInt("method.execution.threshold");
        Profiler profiler = new Profiler(key);
        ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
        profiler.registerWith(profilerRegistry);
        RpcContext.getContext().set("profiler", profiler);
        Result result = invoker.invoke(invocation);
        profiler.stop();
        int spentMs = (int) profiler.elapsedTime() / 1000000;
        if (spentMs > thredshold) {
            logger.error("{} execution time more than {} ms , {} ms has spended", key, thredshold, spentMs);
        }
        String logId =  RpcContext.getContext().getAttachment("logId");
        logger.error("logId is :{},itf and method is {} , args is {} ,ip is {}",logId, key, JSON.toJSONString(invocation.getArguments()), RpcContext.getContext().getLocalAddressString());
        return result;
    }
}
